<?php
namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Session;
use app\common\model\Csuser as CsuserModel;
use app\common\controller\AdminBase;
use app\common\model\Users as UsersModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\model\AdminUser as AdminUserModel;

class Publicnum extends AdminBase
{
    protected $author_wx_user;
    protected $admin_id;
    protected $admin_user_model;
    protected $csuser_model;
    protected $users_model;

    protected function _initialize(){
        parent::_initialize();
        $this->author_wx_user = new AuthorWxUserModel();
        $this->admin_user_model = new AdminUserModel();
        $this->csuser_model = new CsuserModel();
        $this->users_model = new UsersModel();
        $this->admin_id = session::get('admin_id');
    }

    public function index(){
        $where = [
            'w.authorized' => ['eq',1]
        ];

        $where2 = [];
        if($this->admin_id !== 1){
            $where['w.uid'] = ['eq',$this->admin_id];
        }
        // 添加  ,w.wxtype,w.authorized => 20190306 同时修改 author_wx_user model
        $wechat_list = $this->author_wx_user
            ->alias('w')
            ->field('w.id,w.wxname,w.wxtype,w.authorized,w.principal_name,think_admin_user.username as admin_name')
            ->where($where)
            ->join('think_admin_user','w.uid = think_admin_user.id')
            ->select();

        foreach($wechat_list as $wechat){
            $wechat['current_csuser_count'] = $this->csuser_model->field("count(*) as valid_count,(SELECT count(*) FROM think_csuser where auid = {$wechat['id']} AND status = 1 AND type = 1) as online_count")->where('auid',$wechat['id'])->where('status',1)->find();
            $wechat['current_subscribe_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('subscribe_time', 'd')->count();
            $wechat['current_butt_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('create_butt_time', 'd')->count();

            $cs_ids = $this->csuser_model->where('auid',$wechat['id'])->where('status',1)->group('auid')->value('group_concat(id) as cs_ids');
            $wechat['current_msg_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where('send_type',1002)->whereIn('cs_id',$cs_ids)->whereTime('send_time', 'd')->count();
        }

        return $this->fetch('index',[
            'wechat_list' => $wechat_list,
        ]);
    }

    public function index_bk(){
        $where = [
            'w.authorized' => ['eq',1]
        ];
        if($this->admin_id !== 1){
            $where['w.uid'] = ['eq',$this->admin_id];
        }
        $wechat_list = $this->author_wx_user->get_wx_list($where)->toArray();
                        
        foreach($wechat_list as $key => $wechat){
            $wechat_list[$key]['current_csuser_count'] = $this->csuser_model->get_valid_count_and_online_count($wechat);
            // 从user表获取用户, 取得关注数, 速度慢, 采用写入公众号数据的形式存储数据, 然后动态更新
//            $wechat_list[$key]['current_subscribe_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('subscribe_time', 'd')->count();
//            $wechat_list[$key]['current_butt_count'] = $this->users_model->where('auid',$wechat['id'])->whereTime('create_butt_time', 'd')->count();
            $cs_ids = $this->csuser_model->where('auid',$wechat['id'])->where('status',1)->group('auid')->value('group_concat(id) as cs_ids');
            $wechat_list[$key]['current_msg_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where('send_type',1002)->whereIn('cs_id',$cs_ids)->whereTime('send_time', 'd')->count();
        }

//        $len = count($wechat_list);
//
//        for($k = 1;$k < $len;$k++)
//        {
//            for($j = 0;$j < $len - $k;$j++){
//                if($wechat_list[$j]['current_butt_count'] < $wechat_list[$j+1]['current_butt_count']){
//                    $temp =$wechat_list[$j+1];
//                    $wechat_list[$j+1] =$wechat_list[$j] ;
//                    $wechat_list[$j] = $temp;
//                }
//            }
//        }
        return $this->fetch('index',[
            'wechat_list' => $wechat_list,
        ]);
    }

    // 手动更新公众号当天关注数量
    public function update_subnum(){
        $where = [
            'w.authorized' => ['eq',1]
        ];
        if($this->admin_id !== 1){
            $where['w.uid'] = ['eq',$this->admin_id];
        }
        $wechat_list = $this->author_wx_user->get_wx_list($where)->toArray();
        foreach($wechat_list as $key => $wechat){
            // 从user表获取用户, 取得关注数, 速度慢, 采用写入公众号数据的形式存储数据, 然后动态更新
            $current_subscribe_count = $this->users_model->where('auid',$wechat['id'])->whereTime('subscribe_time', 'd')->count();
            //  更新数据到数据库
            $current_butt_count = $this->users_model->where('auid',$wechat['id'])->whereTime('create_butt_time', 'd')->count();
            $data = [
                'current_subscribe_count' => $current_subscribe_count,
                'current_butt_count' => $current_butt_count
            ];
            var_dump($data);
           $reslut =  $this->author_wx_user->where('id',$wechat['id'])->update($data);
            var_dump($reslut);
        }
    }

    public function changetype($id=0){
        $result = $this->author_wx_user->where(['id'=>$id])->select();
//        echo 'hello';
//        dump($result);
        if($id){
            return $this->fetch(
                'changetype' ,[
                    'result'=>$result[0]
                ]
            );
        }
    }

    public function savetype(){
        if(Request::instance()->isPost()){
            $result = Request::instance()->post();
//            dump($id);
//            dump($result); .// UPDATE think_author_wx_user SET wxtype = 'hello' WHERE id = 4
            // Db::name('users')->where('openid', $openid)->update(['is_second_unsubscribe' => 0 ,'subscribe' => 1,'repeat_subscribe' => 1,'subscribe_time' => time()]);
            $changetype = Db::name('author_wx_user')->where('id', $result['id'])->update(['wxtype'=>$result['wxtype']]);
            if ($changetype) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        }
    }

    public function users($wechat_id){
        $admin_users = $this->admin_user_model->field('id,username')->where('status',1)->select();
        return $this->fetch('users',[
            'admin_users' => $admin_users,
            'wechat_id' => $wechat_id
        ]);
    }

    public function author($wechat_id,$uid){
        $result = $this->author_wx_user->save(['uid' => $uid],['id' => $wechat_id]);
        if($result){
            return json(['status' => 1 , 'msg' => '授权成功']);
        }else{
            return json(['status' => -1 , 'error' => '授权失败']);
        }
    }

    public function publicList(){
        $where = [
            'w.authorized' => ['eq',1]
        ];
        if($this->admin_id !== 1){
            $where['w.uid'] = ['eq',$this->admin_id];
        }
        $wechat_list = $this->author_wx_user
                        ->alias('w')
                        ->field('w.id,w.wxname,w.principal_name,think_admin_user.username as admin_name')
                        ->where($where)
                        ->join('think_admin_user','w.uid = think_admin_user.id')
                        ->select();
        foreach($wechat_list as $wechat){
            $wechat['valid_count'] = $this->csuser_model->where('auid',$wechat['id'])->where('status',1)->count();
        }
        return $this->fetch('publicList',[
            'wechat_list' => $wechat_list,
        ]);
    }
}